import { Injectable } from '@nestjs/common';
import { SaveRoleDto } from './dto/role.dto';
import { DataSource, FindManyOptions, In } from 'typeorm';
import { Role } from './entities/role.entity';
import { Permission } from '../permission/entities/permission.entity';
import { Menu } from '../menu/entities/menu.entity';
import { CacheEnum } from '../../../common/constants/redis.constant';
import { RedisService } from '../../../module/shared/redis/redis.service';

@Injectable()
export class RoleService {
  constructor(
    private readonly dataSource: DataSource,
    private readonly redisService: RedisService,
  ) {}

  async save(saveDto: SaveRoleDto) {
    saveDto.permissions = await Permission.find({
      where: {
        id: In(saveDto.permissionIds),
      },
    });
    saveDto.menus = await Menu.find({
      where: {
        id: In(saveDto.menuIds),
      },
    });
    if (saveDto?.id) {
      await this.redisService.deleteKeysByPrefix(CacheEnum.ROLE);
    }
    return await Role.save(Role.create(saveDto));
  }

  async find(options?: FindManyOptions<Role>) {
    return await this.dataSource.manager.find(Role, options);
  }

  async findAndCount(options: FindManyOptions<Role>) {
    const [rows, total] = await this.dataSource.manager.findAndCount(
      Role,
      options,
    );
    return {
      rows,
      total,
    };
  }

  async softDelete(ids: string[]) {
    const result = await this.dataSource.manager.softDelete(Role, ids);
    if (result.affected) {
      await this.redisService.deleteKeysByPrefix(CacheEnum.ROLE);
    }
    return result;
  }
}

export const generateCacheKey = (roleIds: string[]) => {
  return `${CacheEnum.ROLE}:${roleIds.join('')}`;
};
